/***************************************************
1.权限分为 Operator Supervisor admin（权限级别由低到高）
2.每种权限的人只能设置比他级别低的人的权限
******************************************************/

#include "logindialog.h"
#include "ui_logindialog.h"
#include <QMessageBox>
#include <QDebug>
#include "DataBase/databasequery.h"
//#include "dataview/usermodel.h"
#include "common.h"
//#include "statusbar.h"
#include "Dialog/mymessagedialog.h"
//#include "useritemdelegate.h"
//#include "input/hintlineedit.h"
//#include "setting/SysSetting/setpasswordwidget.h"
//#include "SysSetting/syssettingwidget.h"
#include "DataBase/dbtab_user.h"


//#define NAME_TECH    "Technician"

#define BACKDOOR_PASSWD "123456"
#define PW_SUPER_ADMIN "654321"
#define SUPPER_PASSWD "888888"

LoginDialog::LoginDialog(QWidget *parent) :
    TDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    initUser();
    //setWindowFlags(Qt::Dialog);
    connect(ui->loginBtn,SIGNAL(clicked()),this,SLOT(Login()));
    connect(ui->cancelBtn,SIGNAL(clicked()),this,SLOT(clear()));

    ui->comboBox->setFocus();
    ui->comboBox->setEditable(false);

    setModal(false);
    //    this->setFixedSize(SCREEN_WIDTH/3,SCREEN_HIGH/3);
    //    this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    this->move((SCREEN_WIDTH-width())/2,(SCREEN_HIGH-height())/8);
    ui->passwd->setFocus();
    ui->inputKey->hideEscOk();
    ui->inputKey->disableDot();
    ui->inputKey->setClearFlag(true);
    //ui->comboBox->setFocusPolicy(Qt::NoFocus    );

    //=============================
    ui->inputKey->setParmeter(ui->passwd,6,0,"");
    ui->passwd->setText("");
    ui->inputKey->setEditor(ui->passwd);
    ui->inputKey->setMaxLenth(8);
    disconnect(ui->inputKey,0,0,0);
    connect(ui->inputKey,SIGNAL(quitReslut(bool)),this,SLOT(acceptSampleInput(bool)));
    //============================
}

/*
void LoginDialog::textChanged(const QString &str)
{
    if(str.length()==0)
    {
        QFont f("DejaVu Sans",4);
        ui->comboBox->setEditText("Enter User Name");
        //ui->comboBox->setCursor(0);
        ui->comboBox->setFont(f);
    }
    else
    {

        QFont f("DejaVu Sans",6);
        ui->comboBox->setFont(f);
    }
}*/

void LoginDialog::clear()
{
    if(ui->passwd->hasFocus())
    {
        ui->passwd->clear();
    }
    else if(ui->comboBox->hasFocus())
    {
        //ui->comboBox->clear();
        //ui->comboBox->setCurrentIndex(1);
    }
}

void LoginDialog::acceptSampleInput(bool)
{

}


int LoginDialog::checkPassword(int user_code, QString password)
{
    DataBaseQuery query(DataBase::getDataBase());
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QString option = DBTab_User::_TAB_USER_CODE + "=\'" + QString::number(user_code) + "\' AND " +
            DBTab_User::_TAB_USER_PASSWORD + "=\'" + password + '\'';
    query.selectTable(DBTab_User::TAB_USER,NULL,option);
    if(query.size()==1)
    {
        DataBase::getDataBase().commit();
        DataBase::getDataBase().close();
        return query.record().value(DBTab_User::_TAB_USER_PERMISSION).toInt();
    }
    return -1;
}

void LoginDialog::keyPressEvent(QKeyEvent *)
{
    return;
}

QString LoginDialog::technicianString()
{
    return tr("Technician ");
}

void LoginDialog::initUser()
{
    DataBaseQuery query;
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QComboBox *le =  ui->comboBox;
    QStringList str;
    str<<DBTab_User::_TAB_USER_CODE
      <<DBTab_User::_TAB_USER_NAME;
    query.selectTable(DBTab_User::TAB_USER,&str);

    int id = query.record().indexOf(DBTab_User::_TAB_USER_CODE);
    int name = query.record().indexOf(DBTab_User::_TAB_USER_NAME);

    le->addItem("Technician",0);
    //    hideMap.insert(0,true);  ///
    int i=0; ///zhj
    while(query.next())
    {
        i++;
        int custom_id = query.value(id).toInt();
        QString custom_name =  query.value(name).toString();
        le->addItem(custom_name,custom_id);

    }
    le->setCurrentIndex(1);
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
}

LoginDialog::~LoginDialog()
{
    ui->inputKey->setClearFlag(false);
    delete ui;
}

int LoginDialog::mPermission = LoginDialog::TECHNICIAN;
QString LoginDialog::mUser = LoginDialog::technicianString();
bool LoginDialog::mHasLogin = false;
bool LoginDialog::mRecordHide = false;
qint64 LoginDialog::mRFID = -1;
int LoginDialog::permission()
{
    return mPermission;
}

void LoginDialog::setPermission(int permission)
{
    mPermission = permission;
}

void LoginDialog::setLogStatus(bool login)
{
    mHasLogin = login;
}

bool LoginDialog::LogStatus()
{
    return mHasLogin;
}

QString LoginDialog::user()
{
    return mUser;
}

QString LoginDialog::CurrentUser() //MARK0309
{
    QComboBox *cb = ui->comboBox;
    QString user = cb->currentText();
    return user;

}

bool LoginDialog::recordHide()
{
    return mRecordHide;
}

qint64 LoginDialog::getRFIDNumber()
{
    return mRFID;
}
//void LoginDialog::close()
//{
//    permission = UserModel::GUEST;
//    StatusBar::getStatusBar()->changeOperator("Guest");
//    reject();
//}

void LoginDialog::Login()
{
    QComboBox *cb = ui->comboBox;
    int user_code = cb->itemData(cb->currentIndex()).toInt();
    QString user = cb->currentText();
    QString passwd = ui->passwd->text();
    if(QString::compare(user,"Technician",Qt::CaseInsensitive)==0)
    {
        if(QString::compare(passwd,/*SetPasswordWidget::getTechnicianPasswd()*/"000000")==0)
        {
            mPermission = TECHNICIAN;
            mHasLogin = true;
            mRecordHide = false;  ///zhj
            mUser = LoginDialog::technicianString();
            //            StatusBar::getStatusBar()->changeOperator(cb->currentText());
            emit hasLogin();
            accept();
        }
        else if(QString::compare(passwd,"۰۰۰۰۰۰")==0  //波斯语000000
                || QString::compare(passwd,SUPPER_PASSWD)==0)
        {
            //            QSettings set(DIR_SETTINGS,QSettings::IniFormat);
            //            set.beginGroup(SysSettingWidget::GROUP_NAME);
            //            QString str =set.value(SysSettingWidget::PASSWORD_SETTING_NAME).toString();
            //            set.endGroup();
            QString str = "000000";
            if(str.isEmpty())
            {
                mPermission = TECHNICIAN;
                mRecordHide = false;
                mHasLogin = true;

                mUser = LoginDialog::technicianString();
                //                StatusBar::getStatusBar()->changeOperator(cb->currentText());
                emit hasLogin();

                accept();
            }
            else
            {
                goto PASSWD_WRONG;
            }
        }
        else if(QString::compare(passwd,BACKDOOR_PASSWD)==0)
        {
            mPermission = TECHNICIAN;
            mRecordHide = false; ///zhj
            mHasLogin = true;

            mUser = LoginDialog::technicianString();
            //            StatusBar::getStatusBar()->changeOperator(cb->currentText());
            emit hasLogin();

            accept();
        }
        else if(QString::compare(passwd,PW_SUPER_ADMIN)==0)
        {
            mPermission = SUPER_ADMIN;
            mRecordHide = false;
            mHasLogin = true;

            mUser = LoginDialog::technicianString();
            //            StatusBar::getStatusBar()->changeOperator("Super_"+cb->currentText());
            emit hasLogin();

            accept();
        }
        else
        {
            goto PASSWD_WRONG;
        }
    }
    else
    {
        //                UserModel *mode = UserModel::getModel();
        int ret = /*mode->*/checkPassword(user_code,passwd);
        if(ret>=0)
        {
            mPermission = ret;
            //                    mRecordHide = hideMap.value(user_code,false);
            mUser = user;
            mHasLogin = true;
            //changeOperator(cb->currentText());
            //                    StatusBar::getStatusBar()->changeOperator(cb->currentText());
            emit hasLogin();

            accept();
        }
        else
        {
            goto PASSWD_WRONG;
        }

    }
    return;
PASSWD_WRONG:
    ui->passwd->clear();
    MyMessageDialog::warning(0,"Login error","User name or password is wrong!");

}
